package com.dz.finance.wechat.service.impl;

import com.dz.finance.wechat.entity.MpQrCodeCreateReq;
import com.dz.finance.wechat.entity.MpQrCodeCreateResp;
import com.dz.finance.wechat.entity.AccessToken;
import com.dz.finance.wechat.service.WeChatHttpClient;
import com.dz.finance.wechat.service.WeChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author: DengHaoQi
 * @date: 2024/6/4 21:43
 * @description: 调用微信的Api接口
 */


@Slf4j
@Service
@RequiredArgsConstructor
public class WeChatServiceImpl implements WeChatService {

    private final WeChatHttpClient weChatHttpClient;
    private final RedisTemplate<String, Object> redisTemplate;
    final String MP_TOKEN_REDIS_CACHE_KEY = "MP_TOKEN_REDIS_CACHE_KEY:";


    /*
     * 获取接口调用凭证
     * */
    @Override
    public AccessToken getWeChatAccessToken(String appId, String appSecret) {
        return weChatHttpClient.getAccessToken(appId, appSecret);
    }


    /*
     * 将access_token存入缓存
     * */
    @Override
    public void setAccessTokenInCache(String appId, String appSecret) {
        AccessToken accessToken = weChatHttpClient.getAccessToken(appId, appSecret);
        redisTemplate.opsForValue().set(MP_TOKEN_REDIS_CACHE_KEY + appId, accessToken);
    }


    /*
     * 从缓存中获取access_token
     * */
    @Override
    public AccessToken getAccessTokenInCache(String appId) {
        return (AccessToken) redisTemplate.opsForValue().get(MP_TOKEN_REDIS_CACHE_KEY + appId);
    }


    /*
     * 创建二维码
     * */
    @Override
    public MpQrCodeCreateResp createQrCode(String accessToken, MpQrCodeCreateReq mReq) {
        MpQrCodeCreateResp createResp = weChatHttpClient.getTicket(accessToken, mReq);
        try {
            String ticket = URLEncoder.encode(createResp.getTicket(), "utf-8");
            createResp.setQrCodeUrl("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket);
            return createResp;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

    }

}
